
const { ccclass, property } = cc._decorator;

@ccclass
export default class Grid extends cc.Component {

    @property(cc.Node)
    Template: cc.Node = null;

    private _rows: number = 0;
    @property({ step: 1, min: 0 })
    get rows() {
        return this._rows;
    }

    set rows(val: number) {
        this._rows = val;
        this.updateChildren();
    }

    private _cols: number = 0;
    @property({ step: 1, min: 0 })
    get cols() {
        return this._cols;
    }

    set cols(val: number) {
        this._cols = val;
        this.updateChildren();
    }

    private _width = 0;
    @property({ min: 30, step: 1 })
    get width() { return this._width }
    set width(val: number) {
        if (this._width === val) {
            return;
        }
        this._width = val;
        this.updateChildren();
    }

    updateChildren() {
        const rows = this._rows;
        const cols = this._cols;
        const w = this._width;

        this.node.removeAllChildren();

        const layout = this.getComponent(cc.Layout);
        const sx = layout.spacingX;
        const sy = layout.spacingY;
        // top/left/bottom/right === 0
        const width = cols * w + (cols - 1) * sx;
        // const height = rows * w + (cols - 1) * sy;
        this.node.width = width;
        // this.node.height = height;

        for (let i = 0; i < rows * cols; i++) {
            const node = cc.instantiate(this.Template);

            node.active = true;
            node.width = w;
            node.height = w;

            this.node.addChild(node);
        }
    }
}
